<?php

/*
 * Постобработчик шаблонов. 
 * Применяется в классе темы для обработки специфичных тегов T4.
 */

namespace T4;

class Template {

	/**
	 * Постобработка шаблонов - обработка специальных тегов T4
	 * @param string $html HTML для постобработки
	 * @return string Обработанный HTML
	 */
	public static function process($html) {

		/**
		 * <t4:block path="app/block" param1="1" ... />
		 */
		preg_match_all("/<t4:block([\s\S]+?)\/>/i", $html, $matches);

		foreach ($matches[0] as $num => $tag) {

			$attrs = preg_split("/[\s]+/", trim($matches[1][$num]));

			$params = new \stdClass();
			foreach ($attrs as $attr) {
				$p = preg_split("/[\s]*\=[\s]*/", $attr);
				$p[1] = preg_replace("/\"(.*)\"/", "$1", $p[1]);
				$params->{$p[0]} = $p[1];
			}

			list($applicationName, $controllerName, $actionName) = explode('/', $params->id);

                        $block = FrontController::call($applicationName, 'BLOCKS\\' . ucfirst($controllerName), ucfirst($actionName), $params);
                        $application = Application::getInstance($applicationName);
                        $output = new OUTPUT\HTML($application->path . '/templates/blocks/' . ucfirst($controllerName) . '/' . $actionName . '.html');
                        $block = $output->prepare($block);

			$html = str_replace($matches[0][$num], $block, $html);
			
		}

		/**
		 * <t4:(.+) param1="1" ... >(.*)</t4:(.+)>
		 * например t4:editor
		 * 
		 * @todo ХАК С EDITOR заменить на бэк-ссылку!!!
		 * 
		 */
		preg_match_all("/<t4:([a-z0-0_-]+)[\s]+([\s\S]+?)>([\s\S]*?)<\/t4:editor>/i", $html, $matches);

		foreach ($matches[1] as $num => $tag) {

			$action = 'tag' . ucfirst($tag);
			$attrs = preg_split("/[\s]+/", trim($matches[2][$num]));
			$params = new \stdClass();
			foreach ($attrs as $attr) {
				$p = preg_split("/[\s]*\=[\s]*/", $attr);
				$p[1] = preg_replace("/\"(.*)\"/", "$1", $p[1]);
				$params->{$p[0]} = $p[1];
			}

			$result = self::$action($params, $matches[3][$num]);
			$html = str_replace($matches[0][$num], $result, $html);
		}

		return $html;
		
	}

	protected static function tagEditor($params, $content) {
		ob_start();
		require_once \ROOT_PATH . '/include/ckeditor/ckeditor.php';
		$CKEditor = new \CKEditor();
		$CKEditor->basePath = '/include/ckeditor/';
		$CKEditor->editor($params->name, $content);
		$content = ob_get_contents();
		ob_end_clean();
		return $content;
	}

}